package com.dailyblue.project.estate.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Device;
import com.dailyblue.project.estate.commons.handler.DeviceException;
import com.dailyblue.project.estate.commons.mapper.DeviceMapper;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.service.DeviceService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:DeviceServiceImpl
 * @Date:2025/9/18 15:27
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Resource
    private DeviceMapper deviceMapper;
    @Override
    public JsonResult saveDevice(Device device) {
        boolean b = save(device);
        if (!b) {
            throw new DeviceException("添加失败");
        }
        return ResultTool.success("save device success");
    }

    @Override
    public JsonResult findOne(String id) {
        Device device = getById(id);
        return ResultTool.success(device);
    }

    @Cacheable(cacheNames = "AllDevice")
    public JsonResult findAllDevice() {
        List<Device> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "AllDevice",allEntries = true)
    public JsonResult deleteDevice(String id) {
        boolean b = super.removeById(id);
        if (!b) {
            throw new DeviceException("删除失败");
        }
        return ResultTool.success("delete device success");
    }

    @CacheEvict(cacheNames = "AllDevice",allEntries = true)
    public JsonResult updateDevice(Device device) {
        UpdateWrapper<Device> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", device.getId());
        wrapper.set("name", device.getName());
        wrapper.set("community_id", device.getCommunityId());
        wrapper.set("community_name", device.getCommunityName());
        wrapper.set("code", device.getCode());
        wrapper.set("brand", device.getBrand());
        wrapper.set("unit_price", device.getUnitPrice());
        wrapper.set("num", device.getNum());
        wrapper.set("expected_useful_life", device.getExpectedUsefulLife());
        wrapper.set("purchase_date", device.getPurchaseDate());
        int update = deviceMapper.update(wrapper);
        if (update != 1) {
            throw new DeviceException("更新失败");
        }
        return ResultTool.success("update device success");
    }
}
